package com.cskaoyan.controller.user;

import com.cskaoyan.bean.AdminInfoBean;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.InfoData;
import com.cskaoyan.bean.LoginUserData;
import com.cskaoyan.bean.po.ohter.MarketRole;
import com.cskaoyan.bean.po.adminpo.MarketAdmin;
import com.cskaoyan.config.realm.MarketToken;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import com.cskaoyan.util.common.DateUtils;
import com.cskaoyan.util.crypt.CryptUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// shiro整合之后，再做具体的开发
// 响应结果都是JSON，Controller组件上我们都用@RestController注解
@RestController
@RequestMapping("admin/auth")
public class AuthController {

    @Autowired
    MarketAdminMapper adminMapper;
    @Autowired
    MarketRoleMapper marketRoleMapper;

    /**
     * Shiro
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
   /* @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        LoginUserData loginUserData = new LoginUserData();
        AdminInfoBean adminInfo = new AdminInfoBean();
        adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        adminInfo.setNickName("admin123");
        loginUserData.setAdminInfo(adminInfo);
        loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
        return BaseRespVo.ok(loginUserData);
    }
*/
    @PostMapping("login")//登陆
    public BaseRespVo login(@RequestBody Map map, HttpServletRequest request) {
        String username = (String) map.get("username");

        String password = (String) map.get("password");
        // String originPassword = (String) map.get("password");
        // String password = CryptUtils.encryptStr(originPassword);

        String ip = request.getRemoteAddr();
        //在这里要执行登录，Subject.login
        // → Subject只能作为局部变量，不能作为全局变量
        Subject subject = SecurityUtils.getSubject();
        // 执行登录（认证）
        //UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username,password);
        MarketToken authenticationToken = new MarketToken(username, password, "admin");
        try {
            // realm.doGetAuthenticationInfo
            subject.login(authenticationToken);
        } catch (AuthenticationException e) {
            if ("账户错误".equals(e.getMessage())) {
                return BaseRespVo.invalidParameter(e.getMessage());
            }
            return BaseRespVo.invalidParameter("密码错误");
        }

        // 判断是否认证成功
        boolean authenticated = subject.isAuthenticated();
        if (!authenticated) {
            return BaseRespVo.unAuthc();//认证失败
        }
        // 可以获得session信息，也可以获得其sessionId
        Session session = subject.getSession();

        // 获得Principal信息 → realm的doGetAuthorizationInfo方法构造的认证信息里的第一个参数
        MarketAdmin principal = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
        session.setAttribute("username", username);
        session.setAttribute("userId", principal.getId());
        session.setAttribute("principal", principal);

        AdminInfoBean adminInfo = new AdminInfoBean();
        adminInfo.setAvatar(principal.getAvatar());
        // adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        adminInfo.setNickName(principal.getUsername());
        // adminInfo.setNickName("admin123");
        //日志logBean
        LoginUserData loginUserData = new LoginUserData();
        loginUserData.setAdminInfo(adminInfo);
        MarketAdmin adminLoginBo = new MarketAdmin();
        adminLoginBo.setLastLoginIp(ip);
        adminLoginBo.setLastLoginTime(DateUtils.time());
        //更新登陆ip和时间
        adminMapper.updateByPrimaryKey(adminLoginBo);
        //loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
        loginUserData.setToken((String) session.getId());
        //响应sessionId信息给到前端，前端发送请求的时候，通过请求头携带了session的id信息
        return BaseRespVo.ok(loginUserData);
    }

    /* @RequestMapping("info")
     public BaseRespVo info(String token) {
         //开发完shiro之后，再整合
         InfoData infoData = new InfoData();
         infoData.setName("admin123");

         //根据primaryPrincipal做查询
         infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
         ArrayList<String> roles = new ArrayList<>();
         roles.add("超级管理员");
         infoData.setRoles(roles);
         ArrayList<String> perms = new ArrayList<>();
         perms.add("*");
         infoData.setPerms(perms);
         return BaseRespVo.ok(infoData);

     }*/
    @RequestMapping("info")//获取信息
    public BaseRespVo info(String token) {
        //开发完shiro之后，再整合 session域取值
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        if (principals == null) {
            return BaseRespVo.invalidParameter("获取信息失败");
        }
        MarketAdmin principal = (MarketAdmin) principals.getPrimaryPrincipal();
        InfoData infoData = new InfoData();
        infoData.setName(principal.getUsername());
        infoData.setAvatar(principal.getAvatar());

        Integer[] roleIds = principal.getRoleIds();
        List<String> roles = new ArrayList<>();
        List<String> perms = new ArrayList<>();
        for (Integer roleId : roleIds) {
            MarketRole marketRole = marketRoleMapper.selectByPrimaryKey(roleId);
            roles.add(marketRole.getName());
            if("超级管理员".equals(marketRole.getName())){
                perms.add("*");
            }else if("商场管理员".equals(marketRole.getName())){
                perms.add("POST /admin/category/delete");
                perms.add("GET /admin/category/read");
                perms.add("POST /admin/goods/update");
                perms.add("POST /admin/brand/delete");
                perms.add("GET /admin/comment/list");
                perms.add("GET /admin/category/list");
                perms.add("POST /admin/goods/delete");
                perms.add("POST /admin/category/update");
                perms.add("GET /admin/goods/detail");
                perms.add("GET /admin/brand/list");
                perms.add("POST /admin/category/create");
                perms.add("GET /admin/goods/list");
                perms.add("POST /admin/brand/create");
                perms.add("POST /admin/comment/delete");
                perms.add("POST /admin/goods/create");
                perms.add("GET /admin/brand/read");
                perms.add("POST /admin/brand/update");


            }else if("推广管理员".equals(marketRole.getName())){
                perms.add("POST /admin/topic/create");
                perms.add("POST /admin/ad/create");
                perms.add("GET /admin/coupon/listuser");
                perms.add("GET /admin/topic/read");
                perms.add("GET /admin/notice/read");
                perms.add("GET /admin/coupon/list");
                perms.add("POST /admin/groupon/delete");
                perms.add("POST /admin/ad/delete");
                perms.add("POST /admin/ad/update");
                perms.add("GET /admin/ad/list");
                perms.add("POST /admin/notice/create");
                perms.add("POST /admin/groupon/create");
                perms.add("POST /admin/coupon/update");
                perms.add("POST /admin/notice/update");
                perms.add("POST /admin/coupon/delete");
                perms.add("GET /admin/ad/read");
                perms.add("POST /admin/notice/batch-delete");
                perms.add("POST /admin/notice/delete");
                perms.add("GET /admin/groupon/list");
                perms.add("POST /admin/topic/delete");
                perms.add("POST /admin/topic/batch-delete");
                perms.add("POST /admin/groupon/update");
                perms.add("GET /admin/groupon/listRecord");
                perms.add("POST /admin/coupon/create");
                perms.add("GET /admin/topic/list");
                perms.add("GET /admin/coupon/read");
                perms.add("POST /admin/topic/update");
            }
        }
        infoData.setRoles(roles);
        infoData.setPerms(perms);

        return BaseRespVo.ok(infoData);
    }

    @PostMapping("logout")//登出
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok(null);
    }

}
